#!/usr/bin/env python
# encoding: utf-8

import sys
import MySQLdb
import threading

from utils import ConfigSectionMap

reload(sys)
sys.setdefaultencoding("utf-8")

Lock = threading.Lock()


class AppMysql(object):
    __instance = None

    def __init__(self):
        config = ConfigSectionMap("MYSQL")
        self.host = config.get("host")
        self.user = config.get("user")
        self.password = config.get("password")
        self.db = config.get("db")
        self.charset = config.get("charset", "utf8")

    def connect(self):
        return MySQLdb.Connect(host=self.host, user=self.user, passwd=self.password, db=self.db, charset=self.charset)

    def __new__(cls, *args, **kwargs):
        """double check 保证线程安全 """
        if cls.__instance is None:
            try:
                Lock.acquire()
                if cls.__instance is None:
                    cls.__instance = super(cls, AppMysql).__new__(cls, *args, **kwargs)
            finally:
                Lock.release()
        return cls.__instance


appMysql = AppMysql().connect()